/*
board-games:	An educational framework for board games programming.
    Copyright (C) 2008  Daniel Gutson, FuDePAN
    
    This file is part of board-games.

    board-games is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    board-games is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
*/

#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "pipe.h"
#include "shobj.h"
#include "players_side.h"

void PlayerData::load(const char* objname)
{
    const pid_t CHILD = 0;

    // create msg queue:
    //mqueue_to_player.create();
    //mqueue_from_player.create();
    
    //const size_t mqid_to_player = mqueue_to_player.get_id();
    //const size_t mqid_from_player = mqueue_from_player.get_id();
    const size_t random_seed(rand());
    
    pid = fork();
    if (pid==CHILD)
    {
        //PlayerProcess::run(objname, mqid_to_player, mqid_from_player);
        PlayerProcess::run(objname, pipe_to_player, pipe_from_player, random_seed);
    }
}

//void PlayerProcess::run(const char* objname, size_t mqid_to_player, size_t mqid_from_player)
void PlayerProcess::run(const char* objname, const RxPipeHandler& from_referee, const TxPipeHandler& to_referee, size_t random_seed)
{
    signal(SIGSEGV, player_sig_segv_handler);
    {
        //PlayerProcess process(objname, mqid_to_player, mqid_from_player);
        PlayerProcess process(objname, from_referee, to_referee, random_seed);
    }
    //kill(getppid(), SIGALRM);
    exit(EXIT_SUCCESS);
}

//PlayerProcess::PlayerProcess(const char* objname, size_t mqid_to_player, size_t mqid_from_player)
PlayerProcess::PlayerProcess(const char* objname, const RxPipeHandler& from_referee, const TxPipeHandler& to_referee, size_t rand_seed)
    : pipe_from_referee(from_referee), pipe_to_referee(to_referee), random_seed(rand_seed)
{
    typedef Player* CreatePlayer(PlayerAPI*);
    // open msg queue:
    //mqueue_from_referee.open(mqid_to_player);
    //mqueue_to_referee.open(mqid_from_player);
    
    shobj.load(objname);

    CreatePlayer* createPlayerFunc = shobj.load_func<CreatePlayer*>("create_player");
    player = createPlayerFunc(this);
    
    //process_loop();
    player->play();
}


void player_sig_segv_handler(int sig)
{
    kill(getppid(), SIGALRM);
    signal (sig, SIG_DFL);
    raise (sig);
}
